import ResPreloader from "../ResPreloader";
import GameData from "../../global/GameData";
import ScreenFit from "../ScreenFit";
import QuLe from "../sdk/QuLe";
import SDKManager from "../sdk/SDKManager";
import PopupAlert from "../components/PopupAlert";
import Wait from "../components/Wait";

const { ccclass, property } = cc._decorator;

@ccclass
export default class App extends cc.Component {

    @property(cc.ProgressBar)
    loading: cc.ProgressBar = null;

    @property(cc.Prefab)
    wait: cc.Prefab = null;

    @property(cc.Prefab)
    popupAlert: cc.Prefab = null;

    @property(cc.Prefab)
    popupShareTip: cc.Prefab = null;

    @property(cc.Prefab)
    panelChildLock: cc.Prefab = null;

    static instance: App = null;
    resPreloader = new ResPreloader();
    gameData = new GameData();
    isPreloadedRes = false;

    onLoad() {
        App.instance = window.app = this;
        cc.game.addPersistRootNode(this.node);
        this.node.zIndex = 1;//层级高于Canvas

        this.gameData.init();
    }

    /** 外部调用，以便以便结束后执行其他逻辑 */
    init(preloadResList: any[], onFinish: Function) {
        Wait.show();
        QuLe.instance.loadRemoteConfig((success: boolean) => {
            Wait.hide();
            if (success) {
                SDKManager.instance.init();
                if (!this.isPreloadedRes) {
                    console.log('App开始预载资源')
                    //添加资源
                    preloadResList.forEach(element => {
                        this.resPreloader.addRes(element.path, element.type);
                    });
                    //开始加载
                    this.resPreloader.load((progress: number) => {
                        this.loading.progress = progress;
                        if (progress == 1) {
                            console.log('App预载资源完成')
                            this.isPreloadedRes = true;
                            this.loading.node.destroy();
                            if (onFinish) {
                                onFinish();
                            }
                        }
                    });
                } else {
                    if (onFinish) {
                        onFinish();
                    }
                }
            } else {
                PopupAlert.show('初始化Qule失败');
            }
        });
    }

    /** 是否是刘海屏手机 */
    get isLiuHaiScreen(): boolean {
        return (ScreenFit.screenSize.width / ScreenFit.screenSize.height) >= 2.0;
    }
}
